package com.zfc.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zfc.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定以拦截器
 */
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String token = request.getHeader("token");
        try {
            //认证成功直接放行，不做具体业务逻辑处理
            JWTUtil.vertifyToken(token);
            return true;
        }catch (Exception e){
            //认证失败，返回错误信息
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "JWT认证失败！");
        }
        //jackson
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
        response.getWriter().close(); //关闭流
        return false;
    }
}
